package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import domin.BookStatus;
import lombok.extern.slf4j.Slf4j;
import service.BookStautsService;
import util.Condition;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@Slf4j
@WebServlet("/status.ctl")
public class BookStatusController extends HttpServlet {
    private BookStautsService bookStautsService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        try{
            this.responsesBookCategorys(response,null,null);
        }catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }
    private void responsesBookCategorys(HttpServletResponse response, Collection<Condition> condition, Pagination pagination)
            throws ServletException, IOException,SQLException{
        Collection<BookStatus>  bookCategories = bookStautsService.getInstance().findAll(condition,pagination);
        String st_json = JSON.toJSONString(bookCategories, SerializerFeature.DisableCircularReferenceDetect);
        response.getWriter().println(st_json);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String update_json = JSONUtil.getJSON(req);
        BookStatus book = JSON.parseObject(update_json, BookStatus.class);
        System.out.println("1");
        System.out.println(update_json);
        System.out.println(book);
        resp.setContentType("application/json;charset=UTF-8");
        JSONObject message = new JSONObject();
        try {
            bookStautsService.getInstance().update(book);
            message.put("message","修改成功");
        }catch (SQLException e){
            message.put("message","数据库异常");
            log.error("数据库异常" + e.getMessage());
        }catch (Exception e){
            message.put("message","网络异常"+e.getMessage());
            log.error("网络异常");
        }finally {
            resp.getWriter().println(message);
        }
    }
}

